import { ref, inject, hasInjectionContext } from 'vue'

const ToastSymbol = Symbol('toast')

function createToastManager() {
  const toasts = ref([])
  const timers = new Map()
  let uid = 0

  const clearTimer = (id) => {
    if (timers.has(id)) {
      clearTimeout(timers.get(id))
      timers.delete(id)
    }
  }

  const scheduleHide = (id, duration) => {
    if (!duration || duration <= 0) return
    clearTimer(id)
    const timer = setTimeout(() => hide(id), duration)
    timers.set(id, timer)
  }

  const show = (message, type = 'info', duration = 3000) => {
    const id = ++uid
    toasts.value.push({ id, message, type, visible: true })
    scheduleHide(id, duration)
    return id
  }

  const hide = (id) => {
    clearTimer(id)
    const index = toasts.value.findIndex((toast) => toast.id === id)
  if (index !== -1) {
      toasts.value.splice(index, 1)
  }
}

  const clear = () => {
    timers.forEach((timer) => clearTimeout(timer))
    timers.clear()
    toasts.value = []
}

  const success = (message, duration) => show(message, 'success', duration)
  const error = (message, duration) => show(message, 'error', duration)
  const info = (message, duration) => show(message, 'info', duration)
  const warning = (message, duration) => show(message, 'warning', duration)

  return {
    toasts,
    show,
    hide,
    clear,
    success,
    error,
    info, 
    warning,
    showToast: show,
    hideToast: hide,
    clearAll: clear,
  }
}

const defaultManager = createToastManager()

export function installToast(app) {
  app.provide(ToastSymbol, defaultManager)
}

export function useToast() {
  if (hasInjectionContext()) {
    return inject(ToastSymbol, defaultManager)
  }
  // 允许在未注入时（如独立服务）仍使用默认实例
  return defaultManager
}